package com.site.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.site.common.aspect.CurrentUserMethodArgumentResolver;
import com.site.common.filter.RequestFilter;
import com.site.common.interceptor.GlobalInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashSet;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${filter.excludes}")
    private List<String> excludes;
    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public FilterRegistrationBean<RequestFilter> registrationRequestFilterBean(){
        FilterRegistrationBean<RequestFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new RequestFilter(new HashSet<>(excludes),new AntPathMatcher()));
        //filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setOrder(-1);
        return filterRegistrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new GlobalInterceptor())
                .addPathPatterns("/**")
                //.excludePathPatterns(excludes)
                .excludePathPatterns("doc.html","/webjars/**","/v2/api-docs","/v2/**","/favicon.ico","/swagger-resources","/**/*.html","/**/*.js","/**/*.css");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.clear();
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);// 由于实现了WebMvcConfigurer接口，导致jackson全局日志格式化失效，所以需要在这里重新设置
        converters.add(converter);// 将控制器接口返回值转换成json
    }

    @Bean
    public CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver(){
        return new CurrentUserMethodArgumentResolver();
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(currentUserMethodArgumentResolver());
    }
}
